/******************************************************************
 * Copyright @ 2025 FImagine. All rights reserverd.
 * @file   frontend\src\views\ContactsView\ContactItem.tsx
 * @author Gim
 * @date   2025/08/06 10:26
 * @desc   联系人列表条目view
 ******************************************************************/

import ApiInfo from "@/api/ApiV1WxContactGetByUserName_post";
import { ButtonDevOnly } from "@/component/ButtonDevOnly";
import { Show } from "@/component/Display";
import { HighLightText } from "@/component/HighLightText";
import { CancelHolder } from "@/network";
import { show_raw_jsons } from "@/utils/show_raw_jsons";
import { CheckOutlined, CloseOutlined, LoadingOutlined } from "@ant-design/icons";
import { Dropdown, Flex, GetProps, List, Typography } from "antd";
import { ReactNode, useEffect, useMemo, useRef, useState } from "react";
import { contacts_mgr } from "../../mgr/contact/ContactsMgr";
import { IContactItem } from "../../mgr/contact/IContactItem";
import styles from "./styles.module.scss";
const { Text } = Typography
export interface IActionsParams {
  item: ApiInfo.RespData;
  loading: boolean;
}
export interface IContactItemProps extends Omit<GetProps<typeof List.Item>, 'actions'> {
  item: IContactItem;
  show_account?: boolean;
  show_is_friend?: boolean;
  show_username?: boolean;
  show_alias?: boolean;
  dropdown?: GetProps<typeof Dropdown>;
  /**
   * 是否为本地数据，
   * 当此值为真，将向后台请求数据，获取额外信息，比如手机号，手机号在本地是没有的
   */
  is_local?: boolean;
  searching_value?: string;
  actions?: (p: IActionsParams) => ReactNode
}

export function ContactItem(props: IContactItemProps) {
  const {
    item: _item,
    show_account = false,
    show_is_friend = true,
    show_username = true,
    show_alias = true,
    dropdown,
    is_local = false,
    actions,
    searching_value,
    ..._p
  } = props

  const [merged_item, set_merged_item] = useState<ApiInfo.RespData>(_item)
  const [loading, set_loading] = useState(false);
  const ref_jid = useRef<number>(0);
  useEffect(() => {
    if (is_local) {
      set_loading(false)
      const jid = ++ref_jid.current;
      const c = new CancelHolder()
      ApiInfo.call({
        account: _item.account,
        userName: _item.userName
      }, c).then((r) => {
        if (jid !== ref_jid.current) return;
        const merged_item: ApiInfo.RespData = { ...r.data, ..._item }
        set_merged_item(merged_item)
      }).finally(() => {
        if (jid !== ref_jid.current) return;
        set_loading(false)
      })
      return () => c.cancel()
    } else {
      set_merged_item(_item)
    }
  }, [is_local, _item])

  return useMemo(() => {
    const { nickName, remark, userName, account, isFriend, alias, phone } = merged_item || {}
    const prefix =
      userName?.endsWith('@chatroom') ? '群聊: ' :
        userName?.startsWith('gh_') ? '服务号: ' :
          show_account ? '联系人: ' : ''

    const title = (
      <Flex justify='space-between' gap={10}>
        <Text className={styles.title}>
          <Show yes={show_account}>
            <HighLightText search={searching_value}>{account}</HighLightText>
          </Show>
          <Show yes={show_account && prefix}>
            的
          </Show>
          <Show yes={prefix}>
            <Text type='secondary'>
              <HighLightText search={searching_value}>{prefix}</HighLightText>
            </Text>
          </Show>
          <HighLightText search={searching_value}>
            {nickName}
          </HighLightText>

          <Show yes={remark}>
            <Text type='secondary'>
              (备注名: <HighLightText search={searching_value}>{remark}</HighLightText>)
            </Text>
          </Show>
        </Text>

        <Show yes={show_username}>
          <Text type='secondary' title={userName}>
            <HighLightText search={searching_value}>{userName}</HighLightText>
          </Text>
        </Show>
        {loading ? <LoadingOutlined /> : null}
      </Flex>
    )
    const desc = (
      <Flex justify='space-between' gap={10} style={{ display: 'flex' }}>
        <Flex flex={1} gap={10}>
          <Text type='secondary'>
            是否好友{isFriend ? <CheckOutlined /> : <CloseOutlined />}
          </Text>
          <Show yes={show_alias && !!alias}>
            <Text type='secondary'> 微信号:
              <Text strong>
                <HighLightText search={searching_value}>{alias}</HighLightText>
              </Text>
            </Text>
          </Show>
          <Show yes={!!phone}>
            <Text type='secondary'> 手机:
              <Text strong>
                <HighLightText search={searching_value}>{phone}</HighLightText>
              </Text>
            </Text>
          </Show>
        </Flex>
        <Flex gap={10}>
          <Flex gap={10} style={{ flexShrink: 0 }}>
            <ButtonDevOnly label="原始数据" onClick={() => show_raw_jsons([_item])} />
            <ButtonDevOnly label="提交" onClick={() => contacts_mgr.submit(_item)} />
            {merged_item ? actions?.({ loading, item: merged_item }) : void 0}
          </Flex>
        </Flex>
      </Flex>
    )

    const inner = (
      <List.Item
        id={styles.contact_list_item}
        className={styles.contact_list_item}
        {..._p}>
        <List.Item.Meta
          title={title}
          description={desc}
        />
      </List.Item>
    )

    return dropdown ? (
      <Dropdown {...dropdown}>
        {inner}
      </Dropdown>
    ) : inner;
  }, [merged_item, dropdown, loading, searching_value])


}
